Length of last word

Time: O(N); Space: O(1); easy

Given a string s consists of upper/lower-case alphabets and empty space characters ’ ’, return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Example 1:

Input: s = “Hello World”

Output: 5

Note:

  • A word is defined as a maximal substring consisting of non-space characters only.

[1]:
class Solution1(object):
    def lengthOfLastWord(self, s):
        """
        :type s: string
        :rtype: int
        """
        length = 0
        for i in reversed(s):
            if i == ' ':
                if length:
                    break
            else:
                length += 1
        return length
[2]:
sol = Solution1()
s = "Hello World"
assert sol.lengthOfLastWord(s) == 5
[3]:
class Solution2:
    """
    Time: O(N)
    Space: O(N)
    """
    def lengthOfLastWord(self, s):
        """
        :type s: string
        :rtype: int
        """
        return len(s.strip().split(" ")[-1])
[4]:
sol = Solution1()
s = "Hello World"
assert sol.lengthOfLastWord(s) == 5